import { Form } from 'antd';
import { useRequest, useAntdTable } from '@/hooks';
import request from '@/utils/request';
import cmdbres from '@/data/cmdbres';
import enums from '@/enums';

/**
 * 校验验收单名称唯一性
 */
export function useCheckAcceptanceNameUniqueness() {
    return useRequest(
        async (acceptanceMaterialName) => {
            return (
                (
                    await request({
                        ...cmdbres.queryOssAcceptanceList,
                        params: {
                            pageNum: 1,
                            pageSize: 1,
                            acceptanceMaterialName,
                        },
                    })
                ).data.total === 0
            );
        },
        {
            manual: true,
            debounceWait: 300,
        }
    );
}

/**
 * 设备类别标签页配置项
 */
export function useDeviceCategoryTabItems(options) {
    return useRequest(
        async () =>
            (await request({ ...cmdbres.queryModelsInOssAcceptance })).data.map(({ moduleName, cmModuleId }) => ({
                label: moduleName,
                key: cmModuleId,
            })),
        options
    );
}

/**
 * 设备列表列配置
 */
export function useDeviceListColumns(options) {
    return useRequest(async (cmModuleId) => {
        const { data } = await request({
            ...cmdbres.queryModelFieldsInOssAcceptance,
            data: { queryFilter: { EQ: { cmModuleId } } },
        });

        options.onDataSourceSuccess?.(data);

        return data.map(({ propertyName, propertyKey, propertyType, propertyEnumValue }) => {
            const column = {
                title: propertyName,
                dataIndex: propertyKey,
            };

            if (propertyType === 'enum') {
                column.render = (value) => {
                    try {
                        return JSON.parse(propertyEnumValue)[value];
                    } catch (err) {
                        return '-';
                    }
                };
            }

            return column;
        });
    }, options);
}

/**
 * 设备统计映射（设备模型2设备数量）
 */
export function useDeviceStatMapping() {
    const form = Form.useFormInstance();

    return useRequest(async () =>
        (
            await request({ ...cmdbres.queryModelStatInOssAcceptance(form.getFieldValue('cloudRegionCode')) })
        ).data.reduce(
            (prev, curr) => ({
                ...prev,
                [curr.cmModuleId]: curr.total,
            }),
            {}
        )
    );
}

/**
 * 设备标识（待验收）
 */
export function useDeviceIds() {
    const form = Form.useFormInstance();

    return useRequest(
        async ({ cmModuleId, device_type_name, logic_name, sn }) =>
            (
                await request({
                    ...cmdbres.queryResourceIdsInOssAcceptance,
                    data: {
                        cmModuleId,
                        queryFilter: {
                            EQ: {
                                acceptance_status: 'wait_process',
                                cloud_region_code: form.getFieldValue('cloudRegionCode'),
                                device_type_name,
                            },
                            LIKE: {
                                logic_name: logic_name || undefined,
                                sn: sn || undefined,
                            },
                        },
                    },
                })
            ).data,
        { manual: true }
    );
}

/**
 * 设备（根据IDs）
 */
export function useDevicesByIds(cmModuleId, dataSource) {
    return useAntdTable(
        async (tableData) => {
            const { current, pageSize } = tableData;

            const data = dataSource ?? [];
            const currentPageData = data.slice(pageSize * (current - 1), pageSize * current);

            if (currentPageData.length) {
                return {
                    list: (
                        await request({
                            ...cmdbres.queryResourceListInOssAcceptance,
                            data: {
                                cmModuleId,
                                queryFilter: {
                                    IN: {
                                        cm_unid: currentPageData.map(({ resourceId }) => resourceId),
                                    },
                                },
                            },
                        })
                    ).data,
                    total: data.length,
                };
            }

            return [];
        },
        { manual: true }
    );
}

/**
 * 设备列表
 */
export function useDeviceList(cmModuleId, options) {
    const form = Form.useFormInstance();

    return useAntdTable(async (tableData, formData) => {
        const { current, pageSize } = tableData;
        const { device_type_name, logic_name, sn } = formData;

        const { total, data } = await request({
            ...cmdbres.queryResourceListInOssAcceptance,
            data: {
                pageNumber: current,
                pageSize,
                cmModuleId,
                queryFilter: {
                    EQ: {
                        acceptance_status: 'wait_process',
                        cloud_region_code: form.getFieldValue('cloudRegionCode'),
                        device_type_name,
                        sn: sn || undefined,
                    },
                    LIKE: {
                        logic_name: logic_name || undefined,
                    },
                },
                sort: {
                    cm_create_time: 'DESC',
                },
            },
        });

        return {
            total,
            list: data,
        };
    }, options);
}

/**
 * 客户经理
 */
export function useManagers(options) {
    return useRequest(
        async () =>
            (await request({ ...cmdbres.queryOssAcceptanceManagers, data: { groupName: '客响' } })).data.map(
                ({ name, loginName }) => ({
                    customerName: name,
                    customerId: loginName,
                })
            ),
        options
    );
}

/**
 * 工单详情
 */
export function useWorkOrderLink() {
    return useRequest(
        async (id) => {
            const { result } = await request({ ...cmdbres.queryOssAcceptanceWorkOrderLinks, data: { id } });
            const { name } = result[0] ?? {};
            const { remark } = result[1] ?? {};

            return { name, remark };
        },
        {
            manual: true,
        }
    );
}

/**
 * 向验收字段中添加CN字段
 */
function addCNFieldsToAcceptanceFields(data) {
    return {
        cloudRegionTypeCn: enums.ossAcceptance.poolTypes.get(data.cloudRegionType) || undefined,
        applyTypeCn: enums.ossAcceptance.applyTypes.get(data.applyType) || undefined,
        cloudArchitectureCn: enums.ossAcceptance.poolArchs.get(data.cloudArchitecture) || undefined,
        storageTypeCn: enums.ossAcceptance.storageTypes.get(data.storageType) || undefined,
        isSecurityDevicesCn: enums.ossAcceptance.booleans.get(data.isSecurityDevices) || undefined,
    };
}

/**
 * 验收单详情
 */
export function useAcceptanceDetail(options) {
    return useRequest(
        async (acceptanceMaterialId) => {
            const { data } = await request({ ...cmdbres.queryOssAcceptanceDetail, params: { acceptanceMaterialId } });
            return {
                ...data,
                ...addCNFieldsToAcceptanceFields(data),
            };
        },
        {
            manual: true,
            ...options,
        }
    );
}

/**
 * 提交验收单
 */
export function useSubmitAcceptanceForm(options) {
    return useRequest(
        async (params) =>
            await request({
                ...cmdbres[params.acceptanceMaterialId ? 'updateOssAcceptance' : 'createOssAcceptance'],
                data: {
                    ...params,
                    ...addCNFieldsToAcceptanceFields(params),
                },
            }),
        {
            manual: true,
            ...options,
        }
    );
}
